#based on openCV camera.py example and http://www.aishack.in/2010/07/tracking-colored-objects-in-opencv/

import cv2.cv as cv
import time
from Tkinter import *   #
import copy

cv.NamedWindow("camL", 1)
cv.NamedWindow("camR", 1)
cv.NamedWindow("diff", 1)
captureCamL = cv.CaptureFromCAM(0)
captureCamR = cv.CaptureFromCAM(1)

xMax=600
yMax=200


class Run:
    


    def setBack(self):
        # print self.imgNew,self.imgLast
        cv.Copy(self.imgNew,self.imgBack)
        cv.Set(self.imgMarker, cv.Scalar(0,0,0))

    def stepCam(self):
      
        self.imgCamL = cv.QueryFrame(captureCamL)
        self.imgCamR = cv.QueryFrame(captureCamR)
        cv.AbsDiff(self.imgCamL,self.imgCamR,self.imgDiff)
        

        cv.CvtColor(self.imgDiff, self.imgDiff, cv.CV_BGR2HSV)


            
        
        
        cv.CvtColor(self.imgCamL, self.imgCamL, cv.CV_HSV2BGR)
        cv.CvtColor(self.imgCamR, self.imgCamR, cv.CV_HSV2BGR)
        cv.CvtColor(self.imgDiff, self.imgDiff, cv.CV_HSV2BGR)
        cv.ShowImage("camL", self.imgCamL)
        cv.ShowImage("camR", cv.GetMat(self.imgCamR))
        cv.ShowImage("diff", cv.GetMat(self.imgDiff))
   
        
        if cv.WaitKey(50) == 27:
            run.quit()
       

    def __init__(self):
       
        #P.ion()
        #P.xlabel("Evaluations")
        #P.ylabel("Fitness")
       
        self.running = False
        self.first = True
        master = Tk()
        self.frame=Frame(master)
        self.frame.pack()
        c=0
        b = Button(self.frame, text="RUN", fg="black", command=self.run)
        b.grid(row=0,column=c)
        c+=1
        
        b = Button(self.frame, text="BACK ", fg="black", command=self.setBack)
        b.grid(row=0,column=c)
        c+=1
     
     
     
        b = Button(self.frame, text="QUIT ", fg="black", command=self.quit)
        b.grid(row=0,column=c)
        c+=1
     
        self.canvas = Canvas(self.frame, width=xMax, height=yMax+40)
        self.canvas.grid(row=1,columnspan=c)
                  
        self.imgCamL = cv.QueryFrame(captureCamL)
      
  
        

        self.imgDiff = cv.CreateImage(cv.GetSize(self.imgCamL), 8, 3)
      
  
    def quit(self):
        self.running =False
        
        cv.DestroyWindow("camL")
        cv.DestroyWindow("camR")
        cv.DestroyWindow("diff")

        
    def run(self):
        self.running =True
        while self.running:   # ] self.count < MAXITER and self.running:
            self.step();
           

    def step(self):
        
        self.stepCam()
        # give the GUI a chance to do stuff  
        self.frame.update()
        
      
        
if __name__ == '__main__':

    run=Run()
    mainloop() 
